import {
    _decorator,
    Component,
    Node,
    Prefab,
    UITransform,
    log,
    instantiate,
    Vec3,
    Collider2D,
    IPhysics2DContact, Contact2DType, Label,
    AudioSource,
    AudioClip,
} from 'cc';
import {Player} from "db://assets/script/Player";

const {ccclass, property} = _decorator;

@ccclass('GameMgr')
export class GameMgr extends Component {
    @property({type: Prefab}) starPrefab: Prefab = null
    @property({type: Node}) ground: Node = null
    @property({type: Node}) player: Node = null
    @property({type: Label, displayName: "Score (player)"}) scoreLabel: Node = null
    @property(AudioClip) scoreSound: AudioClip;

    score: number = 0;
    // 星星产生后消失时间的随机范围
    maxStarDuration: number = 0;
    minStarDuration: number = 0;
    groundY: number = 0;

    audioSource: AudioSource = null;

    private static _inst: GameMgr;
    public static get inst(): GameMgr {
        return this._inst;
    }
    start() {
        GameMgr._inst = this;
        this.audioSource = this.node.getComponent(AudioSource)!;
        // 获取地平面的 y 轴坐标
        this.groundY = this.ground.position.y + this.ground.getComponent(UITransform).contentSize.height / 2;
        let collider = this.player.getComponent(Collider2D);
        if (collider) {
            collider.on(Contact2DType.BEGIN_CONTACT, this.onCollisionEnter, this);
        }
        // 生成一个新的星星
        this.spawnNewStar();
    }

    update(deltaTime: number) {

    }

    private spawnNewStar() {
        // 使用给定的模板在场景中生成一个新节点
        var newStar = instantiate(this.starPrefab);
        // 将新增的节点添加到 Canvas 节点下面
        this.node.addChild(newStar);
        // 为星星设置一个随机位置
        newStar.setPosition(this.getNewStarPosition());
        console.log("spawnNewStar ------->")
    }


    private getNewStarPosition():Vec3 {
        var randX = 0;
        let playerScript = this.player.getComponent('Player') as Player;
        // 根据地平面位置和主角跳跃高度，随机得到一个星星的 y 坐标
        var randY = this.groundY + Math.random() * playerScript.jumpHeight + 50;
        // 根据屏幕宽度，随机得到一个星星 x 坐标
        var maxX = this.node.getComponent(UITransform).width/2;
        randX = (Math.random() - 0.5) * 2 * maxX;
        // 返回星星坐标
        return new Vec3(randX, randY,0);
    }


    private onCollisionEnter(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact | null){
        otherCollider.node.destroy();
        this.score += 1;
        this.playerSound(this.scoreSound);
        this.spawnNewStar();

        this.scoreLabel.getComponent(Label).string = "Score: "+ this.score

    }


    public playerSound(audioClip:AudioClip ){
        this.audioSource.clip = audioClip;
        this.audioSource.play();
    }
}


